<template>
  <el-row :gutter="20" class="app-container">
    <Splitpanes>
      <pane size="16" v-if="$auth.hasRoleOr(['admin','manager','fishingceo'])">
        <el-col>
          <div class="head-container">
            <el-tree
              :data="deptOptions"
              :props="{ label: 'label', children: 'children' }"
              :expand-on-click-node="false"
              ref="deptTreeRef"
              node-key="id"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick"
            />
          </div>
        </el-col>
      </pane>
    <pane :size="$auth.hasRoleOr(['admin','manager','fishingceo']) ? 84 : 100">
      <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['pond:finace:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pond:finace:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pond:finace:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['pond:finace:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="finaceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="所属钓场" align="center" prop="deptId" />
      <el-table-column label="金额/元" align="center" prop="amount" />
      <el-table-column label="类型：" align="center" prop="type">
        <template #default="scope">
              {{
                scope.row.type == 'INCOME'
                  ? "收入"
                  : "支出"
              }}
            </template>
      </el-table-column>
      <el-table-column label="来源类型" align="center" prop="sourceType" > <template #default="scope">
              {{
                scope.row.sourceType == 'FISH_FLOW'
                  ? "鱼流转"
                  : "其他"
              }}
            </template>
      </el-table-column>
      <el-table-column label="来源记录ID" align="center" prop="sourceId" />
      <el-table-column label="财务描述" align="center" prop="description" />
      <el-table-column label="记录时间" align="center" prop="time" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.time, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['pond:finace:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['pond:finace:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改财务记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="finaceRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属钓场" prop="deptId">
          <DeptSelect
            v-model="form.deptId"
            @change="handleDeptChange"
          />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="来源记录ID" prop="sourceId">
          <el-input v-model="form.sourceId" placeholder="请输入来源记录ID" />
        </el-form-item>
        <el-form-item label="财务描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入财务描述" />
        </el-form-item>
        <el-form-item label="记录时间" prop="time">
          <el-date-picker clearable
            v-model="form.time"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择记录时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
    </pane>
    </Splitpanes>
  </el-row>
</template>

<script setup name="Finace">
import { listFinace, getFinace, delFinace, addFinace, updateFinace } from "@/api/pond/finace"
import { pondOptions } from "@/api/pond/pond";
import DeptSelect from "@/components/DeptSelect/index.vue";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { useDeptTree } from "@/utils/deptTreeUtils";

const { proxy } = getCurrentInstance()

const finaceList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    pondId: null,
    deptId: null,
  },
  rules: {
    deptId: [
      { required: true, message: "所属钓场不能为空", trigger: "blur" }
    ],
    amount: [
      { required: true, message: "金额不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "类型：INCOME收入 / EXPENSE支出不能为空", trigger: "change" }
    ],
    sourceType: [
      { required: true, message: "来源类型，如 RETURN_RECORD / TRANSFER_RECORD不能为空", trigger: "change" }
    ],
    sourceId: [
      { required: true, message: "来源记录ID不能为空", trigger: "blur" }
    ],
    time: [
      { required: true, message: "记录时间不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

// 使用部门树工具
const {
  deptOptions,
  enabledDeptOptions,
  getDeptTree,
  handleFormDeptNodeClick,
  handleSidebarDeptNodeClick,
} = useDeptTree();

/** 查询财务记录列表 */
function getList() {
  loading.value = true
  listFinace(queryParams.value).then(response => {
    finaceList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: null,
    amount: null,
    type: null,
    sourceType: null,
    sourceId: null,
    description: null,
    time: null
  }
  proxy.resetForm("finaceRef")
}

/** 表单中的部门树节点点击事件 */
function handleFormDeptNodeClickLocal(data, node, e) {
  handleFormDeptNodeClick(data, node, e, (deptId) => {
    form.value.deptId = deptId;
  }, proxy, 'deptTreeSelectRef');
}

/** 侧边栏部门树节点单击事件 */
function handleNodeClick(data) {
  handleSidebarDeptNodeClick(data, (deptId) => {
    queryParams.value.deptId = deptId;
    handleQuery();
  });
}

/** 表单中部门选择变化事件 */
function handleDeptChange(deptId) {
  // 当部门改变时，可以在这里添加相关逻辑
  console.log('选择的部门ID:', deptId);
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加财务记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getFinace(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改财务记录"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["finaceRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateFinace(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addFinace(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除财务记录编号为"' + _ids + '"的数据项？').then(function() {
    return delFinace(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('pond/finace/export', {
    ...queryParams.value
  }, `finace_${new Date().getTime()}.xlsx`)
}

getDeptTree();
getList()
</script>
